package br.com.mmm.javacenter.framework.dao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import br.com.mmm.javacenter.framework.configuration.IocController;
import br.com.mmm.javacenter.framework.entity.EntidadeBase;

public class HibernateUtil {
	private static AnnotationConfiguration conf;
	private static SessionFactory factory;
	private static ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<Session>();
	private static Logger logger = Logger.getLogger(HibernateUtil.class);
	static {
		conf = new AnnotationConfiguration();
		for(Class<? extends EntidadeBase<?>> klass:IocController.entityBeans){
			try{
				conf.addAnnotatedClass(klass);
				logger.debug("registrando componente :" + klass.getSimpleName() + " OK");
			}catch (Exception e) {
				logger.debug("registrando componente :" + klass.getSimpleName() + " NOK");
			}
		}
		conf.configure();
		factory = conf.buildSessionFactory();
		factory.getStatistics().setStatisticsEnabled(true);
	}
	
	public static void getStatistics(){
		factory.getStatistics().logSummary();
	}
	
	public static Session getSession() {
		if (sessionThreadLocal.get() == null){
			sessionThreadLocal.set(factory.openSession());	
		} 
		sessionThreadLocal.get().getTransaction().begin();
		return sessionThreadLocal.get();
	}
	
	public static Session getLastCreatedSession() {
		return sessionThreadLocal.get();
	}

	public static void fecharSession() {
		if (sessionThreadLocal.get() != null){
			if(sessionThreadLocal.get().isOpen()){
				Logger.getLogger(HibernateUtil.class).info("FECHANDO SESSION");
				try{
					sessionThreadLocal.get().getTransaction().commit();
				}catch (HibernateException e) {
					
				}finally{
					sessionThreadLocal.get().close();
					sessionThreadLocal.set(null);						
				}
			}
		}
	}
	
	public static void montaBanco() {
		SchemaExport se = new SchemaExport(conf);
		se.create(true, true);
	}
	
	public static void limpaBanco() {
		SchemaExport se = new SchemaExport(conf);
		se.drop(true, true);
	}

	public static void criarSession() {
		if (sessionThreadLocal.get() == null || !sessionThreadLocal.get().isOpen()){
			Logger.getLogger(HibernateUtil.class).info("ABRINDO SESSION");
			sessionThreadLocal.set(factory.openSession());	
		} 		
	}

}
